
import LanguageMng from "./LanguageMng";
import FireBaseMgr from "./FireBaseMgr"
import LogicConfigTs from "../Utils/LogicConfigTs";
import HttpAPIUtil from "../Utils/HttpAPIUtil";
import LanguageMngTs from "./LanguageMngTs";
import UserConfigTs from "./UserConfigTs";
import GameDataUtilTs from "../Utils/GameDataUtilTs";
import RoomTypes from "../Static/RoomTypes";
import RoomConfig from "../Static/RoomConfig";
import LanguageType from "./LanguageType";
import ApkVersionUtil from "../Utils/ApkVersionUtil";
import Channels from "../Static/Channels";
import BaseFunctionMgr from "./BaseFunctionMgr";

cc.Class({
    extends: cc.Component,

    properties: {
        label:{
            default:null,
            type:cc.Label
        },

        progressBar:{
            default:null,
            type:cc.ProgressBar
        },

        testParent:{
            default:null,
            type:cc.Node
        },

        logoSprite:{
            default:null,
            type:cc.Sprite
        },

        frameLogoRoz:{
            default:null,
            type:cc.SpriteFrame
        },

        frameLogo666:{
            default:null,
            type:cc.SpriteFrame
        }
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {




        this.progressBar.node.active = false

        if(!cc.gg){
            cc.gg = {}
            cc.audioEngine.setEffectsVolume(1)
            this._initLogUtils()
            this._initJavaCbs()
        }

        if(!this.__initedMgsAndUtils){
            this.__initedMgsAndUtils = true
            this._initMgsAndUtils()
        }

        this.label.node.active = false
        this._initLanguage(function () {
            this._initStaticLabel()
            this.startChecking()
            RoomConfig.initRooms()
        }.bind(this))

        this.node.on("no_need_hotupdate",this.onNoNeedHotUpdate.bind(this),this)

        this._initGateUI()
        UserConfigTs.loadUserConfig()
        LogicConfigTs.initLogicScene()

        let nativePara = GameDataUtilTs.getIsAllHorizontal()
        let isAllHorizontal = nativePara || 0
        if(!isAllHorizontal) cc.gg.baseUtil.setLandscape(2)
        else cc.gg.baseUtil.setLandscape(1)
    },

    _initBgLogo(){
        if(!this.logoSprite) return
        let channel = cc.gg.gameDataUtil.getPakageChannel() || null;
        if(channel === Channels.CHANNEL_JN){
            this.logoSprite.spriteFrame = this.frameLogo666
        }else {
            this.logoSprite.spriteFrame = this.frameLogoRoz
        }
    },

    _initMgsAndUtils:function () {

        BaseFunctionMgr.initErrorListener()

        let GameController = require("GameController")
        cc.gg.gameCtl = new GameController()

        let HttpUtil = require("HttpUtil")
        cc.gg.httpUtil = new HttpUtil()

        //to restore game data
        let DataMgr = require("DataMgr")
        cc.gg.dataMgr = new DataMgr()

        let EnumConfig = require("EnumConfig")
        cc.gg.enumConfig = new EnumConfig()

        let BaseUtil = require("BaseUtil")
        cc.gg.baseUtil = new BaseUtil()

        let SortUtil = require("SortUtil")
        cc.gg.sortUtil = new SortUtil()

        let ToastMgr = require("ToastMgr")
        cc.gg.toastMgr = new ToastMgr()

        //For restoring of local game data
        let GameDataUtil = require("GameDataUtil")
        cc.gg.gameDataUtil = new GameDataUtil()

        //Util for functions innner of canvas
        let GameLogicUtil = require("GameLogicUtil")
        cc.gg.logicUtil = new GameLogicUtil()

        let ResourceUtil = require("ResourceUtil")
        cc.gg.resUtil = new ResourceUtil()

        let TalkingDataUtil = require("TalkingDataUtil")
        cc.gg.tdUtil = new TalkingDataUtil()
    },

    _initLogUtils:function () {
        let debug_log_flow_show = true
        let debug_log_drag_poker = false
        let debug_log_message = true
        let debug_log_calculate = false
        let debug_log_bottoms = false
        let debug_log_grab = false
        let debug_log_ws = true

        cc.logcal = function (...vars) {
            if(debug_log_calculate)
                cc.log(...vars)
        }

        cc.logfl = function (...vars) {
            if(!debug_log_flow_show)
                return
            cc.log("========flow:",...vars)
        }

        cc.logdrag = function (...vars) {
            if(debug_log_drag_poker)
                cc.log("Log Drag:",...vars)
        }

        cc.logmsg = function (...vars) {
            if(debug_log_message)
                cc.log(...vars)
        }

        cc.logbot = function (...vars) {
            if(debug_log_bottoms)
                cc.log(...vars)
        }

        cc.loggrab = function (...vars) {
            if(debug_log_grab)
                cc.log("grab:",...vars)
        }

        cc.logws = function (...vars) {
            if(debug_log_ws)
                cc.log("ws:",...vars)
        }
    },

    _initLanguage:function (cb) {
        let language = parseInt(cc.sys.localStorage.getItem('language'))
        if(!language){
            let defaultLan = GameDataUtilTs.getDefaultLanguage()
            if(defaultLan){
                language = defaultLan
            }else {
                language = LanguageType.ENGLISH
            }
        }

        cc.log("当前语言为：",language)
        LanguageMng.loadLanguage(language,function () {
            LanguageMngTs.loadLanguage(language,function () {
                if(cb) cb()
            })
        })
    },

    _initStaticLabel:function () {
        this.label.node.active = true
        this.label.string = LanguageMng.getSentence(4)
    },

    _initGateUI:function () {
        if(!CC_DEBUG){
            if(this.testParent) this.testParent.active = false
        }
        this._initBgLogo()
    },

    start () {
        // let a = cc.gg.gameDataUtil.GetRequest()
        // cc.log("-----------------------",a)
        cc.gg.tdUtil.doSendTdEvent("open_gate",null)

        // cc.view.setOrientation(cc.macro.ORIENTATION_PORTRAIT)

        // let result = null
        //
        // let noMix1 = [
        //     {id:3,poker:0x11},
        //     {id:3,poker:0x07},
        //     // {id:3,poker:0x08},
        //     {id:3,poker:0x09},
        //     {id:3,poker:0x0a},
        //     {id:3,poker:0x0b},
        //     {id:3,poker:0x0c},
        // ]
        //
        // let noMix2 = [
        //     {id:3,poker:0x31},
        //     {id:3,poker:0x3c},
        //     {id:3,poker:0x3d},
        // ]
        //
        // result = cc.gg.sortUtil.IS_SEQUENCE(noMix1,1)
        // cc.log("noMix1:",result)
        // result = cc.gg.sortUtil.IS_SEQUENCE(noMix2,1)
        // cc.log("noMix2:",result)
    },

    // update (dt) {},

    onClearTokenButtonClicked:function () {
        cc.sys.localStorage.setItem('user_token', "");
    },

    gateGoLobby:function () {
        cc.gg.gameDataUtil.goToLobby(true)
    },

    gateGoLogin:function () {
        cc.gg.gameDataUtil.goToLogin(true)
    },


    // async startA () {
    //     // init logic
    //     this.label.string = this.text;
    //     let string = await this.testAsync();
    //     cc.log(string)
    // },
    //
    // async testAsync(){
    //     return new Promise((resolver, reject)=>{
    //         setTimeout(() => {
    //             resolver("liang miao yi hou ");
    //         }, 2000);
    //     });
    // },

    // async testAsync() {
    //     return new Promise < string > ((resolve) => {
    //         setTimeout(() => {
    //             resolve ("liang miao yi hou ");
    //         }, 2000);
    //     });
    // },

    async onNoNeedHotUpdate () {
        await cc.gg.toastMgr.showNetWaitting()

        let token = cc.sys.localStorage.getItem("user_token")
        cc.log("从本地取出的token:",token)
        if(token){
            cc.logfl("get token from storage success:",!!token)
            let data = await HttpAPIUtil.getRefreshToken(token);
            cc.log("refresh之后的data:",data)
            let newToken = data?data.token:null
            let uid = data?data.uid:null
            if(newToken){
                cc.gg.tdUtil.doSendTdLogin(uid,"")

                cc.gg.httpUtil.setUserToken(newToken)
                cc.sys.localStorage.setItem('user_token', newToken);
                FireBaseMgr.sendSignUp()

                cc.gg.gameCtl.goLobby(newToken)
                // let loginType = GameDataUtilTs.getLoginType()
                // if(loginType === GameDataUtilTs.LoginMethod.GUEST){
                //     this.gateGoLogin()
                // }else if(loginType === GameDataUtilTs.LoginMethod.MOBILE){
                //     cc.gg.gameCtl.goLobby(newToken)
                // }else {
                //     this.gateGoLogin()
                // }
            }else {
                cc.gg.httpUtil.setUserToken(null)
                this.gateGoLogin()
            }
        }else {
            this.gateGoLogin()
        }
    },

    startChecking:function () {
        // this._startDotMarching()
        if (!cc.sys.isNative) {
            cc.logfl("Not native,skip hot update.")
            cc.find("Canvas").emit("no_need_hotupdate")
            return;
        }
        // else {
        //     cc.find("Canvas").emit("no_need_hotupdate")
        //     return
        // }


        let gatehuScript = this.node.getComponent("GateHotUpdate")
        gatehuScript.initGateHotUpdate(this)
        gatehuScript.startHotUpdate()
    },

    changeIndicatorLabel:function (string) {
        this.label.string = string
    },

    showGateProgress:function (show) {
        this.progressBar.node.active = show
    },

    changeGateUpdateProgress:function (percent) {
        this.progressBar.progress = percent
    },

    _initJavaCbs:function () {

        // let aaa = 861/2135/1440
        // cc.log("=======",aaa)
        cc.game.onKeyboardUp = function (androidScreenHeight,keyboardHeight) {
            let boardHInCocos = 0;
            //为了兼容老版本只有一个参数（键盘高度）传进来的情况
            if(!keyboardHeight && keyboardHeight != 0){
                keyboardHeight = androidScreenHeight
                boardHInCocos = keyboardHeight
            }else {
                boardHInCocos = keyboardHeight/(androidScreenHeight/1440)
                cc.log("原生屏幕高度："+androidScreenHeight+"，原生键盘高度"+keyboardHeight+"，内容实际下移距离："+boardHInCocos)
            }


            console.log("JAVA调用了 onKeyboardUp",keyboardHeight)
            let upCbs = cc.gg.gameDataUtil.keyboardUpCbs
            for(let i in upCbs){
                let cb = upCbs[i]
                if(cb){
                    cb(boardHInCocos)
                }
            }
        }

        cc.game.onKeyboardDown = function (height) {
            console.log("JAVA调用了 onKeyboardDown",height)
            let upCbs = cc.gg.gameDataUtil.keyboardDownCbs
            for(let i in upCbs){
                let cb = upCbs[i]
                if(cb){
                    cb(height)
                }
            }
        }

        cc.game.uploadFileFinish = async function (num,resJson) {
            console.log("JAVA调用了uploadFileFinish",num)
            if(num == 1){   //KYC
                cc.gg.toastMgr.removeNetWaitting()
                cc.gg.toastMgr.showToast("KYC Image upload success!")
                cc.find("Canvas").emit("kyc_update_pan_updated")
            }if(num == 2){  //CAMERA
                await cc.gg.logicUtil.uploadFaceImgUrl(resJson.data.img)
                cc.gg.toastMgr.removeNetWaitting()
                cc.gg.toastMgr.showToast("Face image upload success!")
                cc.find("Canvas").emit("config_refresh_face")
                this.uiMgr.updateLobbyUser()
            }else {
                cc.gg.toastMgr.removeNetWaitting()
                cc.gg.toastMgr.showToast("Image upload failed!")
            }
        }

        cc.game.onThirdLogin = async function (channelId,loginToken,packChannel) {
            console.log("JAVA调用了onThirdLogin",channelId,loginToken,packChannel)
            if(channelId == 1){
                await cc.gg.toastMgr.showNetWaitting()
                let result = await cc.gg.httpUtil.httpPost("/user/login/google",{token:loginToken,channel:packChannel})
                if (!result.succ) {
                    cc.gg.toastMgr.removeNetWaitting()
                    cc.gg.toastMgr.showToast(LanguageMng.getSentence(177))
                    console.error(`Google登陆失败: ${result.msg}`);
                    return;
                }
                cc.logfl(`Google登陆成功, 用户名: ${result.data.username}, 密码: ${result.data.password}`);
                console.log(result.data);
                let token = result.data.token
                cc.sys.localStorage.setItem('user_token', token);
                cc.gg.httpUtil.setUserToken(token)
                cc.gg.toastMgr.removeNetWaitting()

                let loginScript = cc.find("Canvas").getComponent(LogicConfigTs.SCENENAME_LOGIN)
                if(!loginScript){
                    cc.error("当前场景不是Login！")
                    return
                }
                cc.gg.gameDataUtil.isRegister = true
                cc.gg.gameCtl.goLobby(token)
            }else if(channelId == 2){
                await cc.gg.toastMgr.showNetWaitting()
                let result = await cc.gg.httpUtil.httpPost("/user/login/facebook",{token:loginToken,channel:packChannel})
                if (!result.succ) {
                    cc.gg.toastMgr.removeNetWaitting()
                    cc.gg.toastMgr.showToast(LanguageMng.getSentence(177))
                    console.error(`Facebook登陆失败: ${result.msg}`);
                    return;
                }
                cc.logfl(`facebook登陆成功, 用户名: ${result.data.username}, 密码: ${result.data.password}`);
                let token = result.data.token
                console.log(result.data.uid);
                console.log(result.data.token);

                cc.sys.localStorage.setItem('user_token', token);
                cc.gg.httpUtil.setUserToken(token)
                cc.gg.toastMgr.removeNetWaitting()

                let loginScript = cc.find("Canvas").getComponent(LogicConfigTs.SCENENAME_LOGIN)
                if(!loginScript){
                    cc.error("当前场景不是Login！")
                    return
                }
                cc.gg.gameCtl.goLobby(token)
                cc.gg.gameDataUtil.isRegister = true
            }
        }
    },
});
